package com.chenx.myapplicationnav.ui.home

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import okhttp3.OkHttpClient
import okhttp3.Request
import okio.IOException
import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import org.jsoup.select.Elements

class HomeViewModel : ViewModel() {

//    private val _text = MutableLiveData<String>().apply {
//        value = "This is home Fragment"
//    }
//    var text: LiveData<String> = _text
//
//
//    private val _testlist= MutableLiveData<List<String>>().apply {
//        // 初始化多个数据
//        value = listOf("Item 1123123", "Item 2", "Item 3")
//    }
//    var textlist:LiveData<List<String>> = _testlist


    public var _images = MutableLiveData<List<String>>()
    var images: MutableLiveData<List<String>> = _images

    //    lateinit var webSite:WebSite
    init {
        //   webSite=ChinaZ()
    }

    fun fetchImages(url: String) {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                val client = OkHttpClient()
                val request = Request.Builder().url(url).build()
                val response = client.newCall(request).execute()
                val html = response.body?.string()

                if (html != null) {
                    val doc: Document = Jsoup.parse(html)
                    val imageElements: Elements = doc.select("img")

                    val imageUrls = imageElements.map { it.attr("src") }
                    _images.postValue(imageUrls)
                }
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
    }
}